package com.lark.utils;

import com.lark.exception.FileException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 解析resources目录下文件工具类
 */
public final class ResourcesUtil {

    private ResourcesUtil() {
    }

    /**
     * 解析资源文件
     *
     * @param filePath
     * @return
     */
    public static String parse(String filePath) {
        InputStream inputStream = ResourcesUtil.class.getClassLoader().getResourceAsStream(filePath);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            // 读取整个文件内容
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {
            throw new FileException("文件解析异常: " + e.getMessage());
        }
    }

    public static List<String> parseList(String filePath) {
        List<String> list = new ArrayList<>();
        InputStream inputStream = ResourcesUtil.class.getClassLoader().getResourceAsStream(filePath);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String readLine = null;
            while ((readLine = reader.readLine()) != null) {
                list.add(readLine);
            }
        } catch (IOException e) {
            throw new FileException("文件解析异常: " + e.getMessage());
        }
        return list;
    }

    /**
     * 解析资源文件
     *
     * @param filePath
     * @param charset
     * @return
     */
    public static String parse(String filePath, String charset) {
        InputStream inputStream = ResourcesUtil.class.getClassLoader().getResourceAsStream(filePath);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {
            // 读取整个文件内容
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {
            throw new FileException("文件解析异常: " + e.getMessage());
        }
    }

    /**
     * 资源文件路径转换
     *
     * @param filePath 文件路径
     * @return 转换后的文件路径
     */
    public static String convertFilePath(String filePath) {
        return ResourcesUtil.class.getClassLoader().getResource(filePath).toExternalForm();
    }
}
